<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               :title="'卡片' + '(' + dataForm.realName + ' ' + dataForm.username + ')'"
               :modal="false"
               class="user-dialog add-or-updata"
               width="80%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <template>
        <el-button type="primary"
                   plain
                   icon="el-icon-plus"
                   style="margin-bottom: 20px;"
                   @click="addCard = true">新增</el-button>
      </template>
      <table-template :tableData='tableData'
                      :loading='dataListLoading'
                      :fieldManagement='false'
                      height="300px"
                      :dataList='dataList'>
        <template slot="number-after">
          <el-table-column prop="type"
                           align="center"
                           label="卡类型"
                           min-width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.type === -1">其他</span>
              <span v-if="scope.row.type === 0">IC卡</span>
              <span v-if="scope.row.type === 1">RFID卡</span>
              <span v-if="scope.row.type === 2">CPU卡</span>
            </template>
          </el-table-column>
        </template>
        <template slot="number-after">
          <el-table-column prop="status"
                           align="center"
                           label="状态"
                           min-width="80">
            <template slot-scope="scope">
              <span :class="scope.row.status === 0 ? 'error': 'success'">{{ scope.row.status === 0 ? '停用' : '正常' }}</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column :label="$t('handle')"
                         fixed='right'
                         header-align='center'
                         align='center'
                         width='100'>
          <template slot-scope='scope'>
            <el-button type='text'
                       class='brand'
                       @click="changeCardStatus(scope.row)"
                       size='small'>{{ scope.row.status === 0 ? '启用' : '停用' }}</el-button>
          </template>
        </el-table-column>
      </table-template>
    </el-dialog>
    <el-dialog :visible.sync='addCard'
               width="50%"
               title="新增卡片"
               class="user-dialog add-or-updata"
               :append-to-body="true"
               :before-close="handleClose"
               :close-on-press-escape="false"
               :close-on-click-modal="false">
      <template>
        <el-form :model="data"
                 :rules="dataRule"
                 label-position="left"
                 ref="data"
                 @keyup.enter.native="dataActionSubmitHandle()"
                 label-width="120px">
          <el-form-item prop="number"
                        label="卡号">
            <el-input v-model.trim="data.number"
                      placeholder="请输入卡号"></el-input>
          </el-form-item>
          <el-form-item prop="type"
                        label="卡类型">
            <el-select v-model="data.type"
                       size="min"
                       placeholder="请选择">
              <el-option v-for="item in typeList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template slot="footer">
        <el-button @click="handleClose()">{{ $t('cancel')}}</el-button>
        <el-button type="primary"
                   :loading="confirmLoading"
                   @click="dataActionSubmitHandle()">{{ $t('confirm')}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableTemplate from '@/components/table-template'
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
export default {
  mixins: [mixinViewModule, minFormValidate],
  props: {
  },
  data () {
    return {
      mixinViewModuleOptions: {
        activatedIsNeed: false,
        getDataListURL: 'system/sysUserCard/getListByUserId', // 数据列表接口，API地址
        getDataListIsPage: false, // 数据列表接口，是否需要分页？
        addOrUpdateURL: '', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      selectItems: [],
      visible: false,
      addCard: false,
      type: [],
      dataList: [],
      dataForm: {},
      confirmLoading: false,
      data: {
        number: '',
        type: ''
      },
      typeList: [
        {
          id: -1,
          name: '其他'
        }, {
          id: 0,
          name: 'IC卡'
        }, {
          id: 1,
          name: 'RFID卡'
        }, {
          id: 2,
          name: 'CPU卡'
        }
      ]
    }
  },
  mounted () {
  },
  components: { tableTemplate },
  computed: {
    tableData () {
      return [
        { label: '卡号', width: '100', prop: 'number' },
        { label: '备注', width: '150', prop: 'marks' },
        { label: '更新人', width: '100', prop: 'updaterName' },
        { label: '更新时间', width: '150', prop: 'updateDate' },
        { label: '创建人', width: '100', prop: 'creatorName' },
        { label: '创建时间', width: '150', prop: 'createDate' }
      ]
    },
    dataRule () {
      let validatePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else if (value.length > 16) {
          callback(new Error('请输入8-16位,支持大写字母,数字'))
        } else {
          // let pPattern = /^.*(?=.*\d)(?=.*[A-Z]).{8,16}/
          let pPattern = /^[0-9A-Z]{8,16}$/
          let tempString = ''
          // let order = 0 // 顺序
          if (value.length > 4) {
            tempString = value.substring(0, 5)
          }
          console.log(tempString)
          if (pPattern.test(value) && tempString !== 'KJXNK') {
            callback()
          } else if (pPattern.test(value) && tempString === 'KJXNK') {
            callback(new Error('卡号前缀不能为\'KJXNK\''))
          } else {
            callback(new Error('请输入8-16位,支持大写字母,数字'))
          }
        }
      }
      return {
        number: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' },
          { validator: validatePassword, trigger: 'change' }
        ],
        type: { required: true, message: '请选择类型', trigger: 'change' }
      }
    }
  },
  methods: {
    closeDialog () {
      this.visible = false
      this.$emit('callBack')
    },
    init (data) {
      if (data) {
        this.dataForm.userId = data.id
        this.dataForm.realName = data.realName
        this.dataForm.username = data.username
      }
      this.visible = true
      this.getDataList()
    },
    handleClose () {
      this.data.number = ''
      this.data.type = ''
      this.addCard = false
    },
    dataActionSubmitHandle () {
      this.$refs['data'].validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          this.data.userId = this.dataForm.userId
          this.$http.post('system/sysUserCard/', this.data).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$message.success('添加成功')
            this.confirmLoading = false
            this.getDataList()
            this.handleClose()
          })
        }
      })
    },
    changeCardStatus (data) {
      let text = data.status === 0 ? '是否启用该卡片？' : '是否停用该卡相关业务？'
      this.$confirm(text, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定进行的操作
        let obj = {}
        obj.id = data.id
        obj.status = data.status === 0 ? 1 : 0
        this.$http.put('system/sysUserCard/updateStatus', obj).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success('修改成功')
          this.getDataList()
        })
      }).catch(() => {
        // 点击取消进行的操作
        return false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.error {
  color: red;
}
</style>
